//
//  UIApplication+FPlugin.m
//  FFoundation
//
//  Created by 三井 on 2019/11/7.
//

#import "UIApplication+FPlugin.h"
#import "FPluginHost.h"
#import "FPluginCallFake.h"

@implementation UIApplication (FPlugin)

@end

@implementation FPluginCallCommend

+ (instancetype)callCommend:(void (NS_NOESCAPE ^)(FPluginCallCommend * _Nonnull))build {
    FPluginCallCommend *cmd = [[FPluginCallCommend alloc] init];
    build(cmd);
    return cmd;
}

@end

id _Nullable PluginCall(NSString * _Nullable selfid, NSString * _Nullable target, NSString * _Nonnull method, NSDictionary * _Nullable params, FPluginCallCommendCallback callback) {
    FPluginCallCommend *cmd = [FPluginCallCommend callCommend:^(FPluginCallCommend * _Nonnull cmd) {
        cmd.srcid = selfid;
        cmd.tarid = target;
        cmd.method = method;
        cmd.params = params;
        cmd.callback = callback;
    }];
    return PluginCommendCall(cmd);
}

id _Nullable PluginCommendCall(FPluginCallCommend * _Nonnull commend) {
    for (id<FPluginCallable> plugin in UIApplication.sharedApplication.pluginHost.plugins) {
        if (commend.tarid && ![commend.tarid isEqualToString:[plugin.class identifier]]) continue;
        
        F_macro_delegate_return(id, plugin, @selector(pluginCall:), commend);
        
        if (F_macro_delegate_result) {
            return F_macro_delegate_result;
        }
    }
    return nil;
}

id _Nullable PluginProtocol(Protocol *ptl) {
    for (id<FPluginCallable> plugin in UIApplication.sharedApplication.pluginHost.plugins) {
        if ([plugin respondsToSelector:@selector(pluginBind)]) {
            if ([[plugin pluginBind] containsObject:ptl]) {
                return [FPluginCallFake fakeFor:plugin];
            }
        }
    }
    return nil;
}
